import socketIo from 'socket.io-client'
import local from '@/utils/local'
// const  socketIo  = require('@/utils/vue-socketio')

class socketIoClass {
  constructor(url) {
    this.instance = null
    this.timer = null
    this.commonFun = null
  }
  static getInstance() {
    return this.instance
  }
  connect(SOCKET_IO_URL,commonFun) {
    if(this.instance){
      this.instance.close()
    }
    if(commonFun)this.commonFun =commonFun
    // console.log('connect-begin')
    this.instance = socketIo.connect(SOCKET_IO_URL, {
      transports: ["websocket"],
      reconnection: true,
      timeout: 300000, // connect_error和connect_timeout事件触发前的延迟时间
      reconnectionDelayMax: 1000, // 最大的重连等待时间
      reconnectionDelay: 1000, // 重新创建连接的延迟时长
      // reconnectionAttempts: 5 // 尝试重连的次数
    })
    this.onConnect()
    this.onMessage(this.commonFun)
  }
  onConnect() {
    this.instance.on('connect', () => {
      console.log('socket-io连接上啦！！！！')
      // 连接成功后向服务器发送消息
      this.instance.emit('client_init_event')
      if (!local.get('socketConnect')) {
        local.set('socketConnect', true)
      }
    })
  }
  onMessage(callback) {
    this.instance.connected = true;
    this.instance.on('push_data_event', data => {
      console.log('socket-io收到消息啦！！！！', data)
      if (callback && typeof callback === 'function')callback(data)
      return data
    })
  }
  onDisConnect(SOCKET_IO_URL) {
    // 连接断开
    this.instance.on('disconnect', () => {
      console.log('socket-io连接断开！！！！')
      if(local.get('socketConnect')){
        if(this.instance&&!this.instance.connected&&!this.timer){
          this.timer = setInterval(()=>{
            if(this.instance&&this.instance.connected){
              if(this.timer){
                clearInterval(this.timer)
                this.timer = null
              }
            }else {
              console.log(new Date().getTime())
              this.connect(SOCKET_IO_URL)
            }
          },30000)
        }
      }
    })
  }
  onError(callback) {
    // 连接错误
    this.instance.on('error message', msg => {
      console.log('error:' + msg)
    })
  }
  close() {
    if (this.instance) this.instance.close()
    console.log('socket-io关闭啦！！！！')
  }
}
export default socketIoClass
